package com.bh.ly.oa.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.bh.ly.oa.R;

public class Util {

	public static int getDrawableByName(String name) {
        return getResId(name, R.drawable.class);
    }
    
    public static int getResId(String variableName, Class<?> с) {

        Field field = null;
        int resId = 0;
        try {
            field = с.getField(variableName);
            try {
                resId = field.getInt(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resId;
    }
    
	public static String getBody(InputStream io) {
		StringBuffer buffer = new StringBuffer();
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(io,
					"utf8");
			BufferedReader bodyReader = new BufferedReader(inputStreamReader);
			String line = bodyReader.readLine();
			while (line != null) {
				buffer.append(line);
				line = bodyReader.readLine();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}
	
	/*
	 * 
	 * get reponse Data
	 */
	
	public static BasicHttpContext instance;	
	public static CookieStore cookieStore;
	public static String suppliercode;
	public static synchronized BasicHttpContext getBasicHttpContextInstance(){
		if(instance==null){
			instance=new BasicHttpContext();
		}
		return instance;
	}
	
	public static String getResponseBody(String requrl){
	   	try{
	   		DefaultHttpClient httpClient = new DefaultHttpClient();
	   		HttpGet httpGet = new HttpGet(requrl);
			if(cookieStore!=null)
				httpClient.setCookieStore(cookieStore);
			HttpResponse response=httpClient.execute(httpGet,getBasicHttpContextInstance()); 
			if(cookieStore==null)
				cookieStore=httpClient.getCookieStore();
			HttpEntity httpEntity = response.getEntity();
			return getBody(httpEntity.getContent());
        	}catch(Exception e){
        		e.printStackTrace();
        		return "";
        	}
	}
	
	public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        }
        return false;
    }
}
